package com.name.givename.serviceimpl;

import com.github.pagehelper.Page;
import com.name.givename.dao.UserBonusInfoEntityMapper;
import com.name.givename.dto.BonusInfoDTO;
import com.name.givename.entity.UserBonusInfoEntity;
import com.name.givename.enums.ResultEnum;
import com.name.givename.exception.ServiceException;
import com.name.givename.param.UserOpenRedpackParams;
import com.name.givename.result.ResultVoUtils;
import com.name.givename.service.UserBonusInfoService;
import com.name.givename.utils.Redpack;
import com.name.givename.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.name.givename.entity.UserAndBonusEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by yangtianrui on 18/9/2.
 */
@Transactional
@Service
@Slf4j
public class UserBonusInfoServiceImpl implements UserBonusInfoService {

    @Autowired private UserBonusInfoEntityMapper bonusInfoEntityMapper;
    private static  long ONE_DAY_MONEY = 14500;  // 总金额
    private static  Integer ONE_DAY_COUNT = 50000;  // 红包个数

    /**
     * 获取红包 随机
     * @param userOpenRedpackParams
     * @return
     */
    @Override
    public  synchronized Result<List<BonusInfoDTO>>  getRedPack(UserOpenRedpackParams userOpenRedpackParams) {
        if (userOpenRedpackParams.getOpenId() == null) {
            throw new ServiceException(ResultEnum.USER_OPENID_NULL.getCode(),ResultEnum.USER_OPENID_NULL.getValue());
        }
        List<BonusInfoDTO> AvailableRedPacks = new ArrayList<>();
        System.out.println(System.currentTimeMillis()/1000);
        // 获取当前时间内的可领取红包
        AvailableRedPacks = bonusInfoEntityMapper.getRedPackList(System.currentTimeMillis()/1000);
        int todayCount = AvailableRedPacks.size();
        System.out.println(todayCount+"======");
        if (todayCount <= 0) {
            return ResultVoUtils.error(1,"今日份的红包已被领完，明天早点来");
        }
        BonusInfoDTO result =  AvailableRedPacks.stream().filter
                (x->x.getWin_status() != 1).collect(Collectors.toList()).get(0);
        if(result != null) {
            UserBonusInfoEntity entity = bonusInfoEntityMapper.selectByPrimaryKey(result.getBonus_id());
            entity.setOpenId(userOpenRedpackParams.getOpenId());
            entity.setWinStatus("1");
            bonusInfoEntityMapper.updateByPrimaryKey(entity);
        }
        AvailableRedPacks.remove(result);
        System.out.println(AvailableRedPacks.size());
        System.out.println(todayCount);
        return ResultVoUtils.success(result);
    }

    /**
     *  发送红包
     *  生成5万个空红包
     * @return
     */
    @Override
    public List<BonusInfoDTO> sendRedPack() {
        // 生成随机的红包金额 第一天发送
        List<Double> list = Redpack.openRedPacket(ONE_DAY_MONEY, ONE_DAY_COUNT);
        List<UserBonusInfoEntity> bonusInfoEntities = new ArrayList<>();
        bonusInfoEntities = list.stream().map(x -> {
            UserBonusInfoEntity bonusInfoEntity = new UserBonusInfoEntity();
            bonusInfoEntity.setWinMoney(x);
            bonusInfoEntity.setWinStatus("0"); //  红包中奖状态
            bonusInfoEntity.setWithdrawStatus("0"); // 默认未提现
            return bonusInfoEntity;
        }).collect(Collectors.toList());
        //  批量插入红包到数据库
        bonusInfoEntityMapper.batchInsert(bonusInfoEntities);
        //List<BonusInfoDTO> bonusInfoDTOList = bonusInfoEntityMapper.getRedPackList();
        //System.out.println(bonusInfoDTOList.size());
        // TODO
        return null;
    }

    /**
     * 红包提现排行榜
     * @return
     */
    @Override
    public Page<UserAndBonusEntity> getUserAndBonus() {
        Page<UserAndBonusEntity> userAndBonusEntities = bonusInfoEntityMapper.getUserAndBonus();
        if (CollectionUtils.isEmpty(userAndBonusEntities)) {
            return null;
        }
        return new Page(){{
            this.setPages(userAndBonusEntities.getPages());
            this.setPageNum(userAndBonusEntities.getPageNum());
            this.setPageSize(userAndBonusEntities.getPageSize());
            this.setTotal(userAndBonusEntities.getTotal());
            this.addAll(userAndBonusEntities.stream().map(userAndBonusEntity -> new UserAndBonusEntity(){{
                this.setHeadImgUrl(userAndBonusEntity.getHeadImgUrl());
                this.setPhone(userAndBonusEntity.getPhone().substring(0,3)+"****"+userAndBonusEntity.getPhone().substring(7,11));
                this.setOpenId(userAndBonusEntity.getOpenId());
                this.setWinMoney(userAndBonusEntity.getWinMoney());
            }}).collect(Collectors.toList()));
            }};
    }

    @Override
    public List<UserAndBonusEntity> getBonusCount(String openId) {
        if ("".equals(openId) || openId == null) {
            throw new ServiceException(ResultEnum.USER_OPENID_NULL.getCode(),ResultEnum.USER_OPENID_NULL.getValue());
        }
       return bonusInfoEntityMapper.userBonusCounts(openId);
    }
}


